/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: SplashActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.main.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.io.File;
import java.math.BigDecimal;

import io.bhex.app.BuildConfig;
import io.bhex.app.R;
import io.bhex.app.app.BHexApplication;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.main.presenter.SplashPresenter;
import io.bhex.app.safe.SafeUilts;
import io.bhex.app.utils.BasicFunctionsUtil;
import io.bhex.app.utils.TextColorUtils;
import io.bhex.app.view.CustomListAlertDialog;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.core.SPEx;
import io.bhex.sdk.UrlsConfig;
import io.bhex.sdk.app.AppStatusConstant;
import io.bhex.sdk.app.AppStatusManager;
import io.bhex.sdk.data_manager.MMKVManager;
import io.bhex.sdk.data_manager.RateAndLocalManager;

import static io.bhex.sdk.UrlsConfig.API_SERVER_URL;
import static io.bhex.sdk.UrlsConfig.REST_URL_DEV;
import static io.bhex.sdk.UrlsConfig.REST_URL_ONLINE;
import static io.bhex.sdk.UrlsConfig.REST_URL_PREV;
import static io.bhex.sdk.UrlsConfig.REST_URL_TEST;

/**
 * ================================================
 * 描   述：App 启动页面
 * ================================================
 */

public class SplashActivity extends BaseActivity<SplashPresenter, SplashPresenter.SplashUI> implements SplashPresenter.SplashUI, View.OnClickListener {
    private static final String DEFAULT_SHOW_DURATION_TIME = "1.5";   //默认显示时长
    private ImageView launchBgView;
    private TextView btnSkip;
    private CountDownTimer showCountDownTimer;

    @Override
    protected int getContentView() {
        return R.layout.activity_splash_layout;
    }

    @Override
    protected SplashPresenter createPresenter() {
        return new SplashPresenter();
    }

    @Override
    protected SplashPresenter.SplashUI getUI() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//          requestWindowFeature(Window.FEATURE_NO_TITLE);
//          getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        AppStatusManager.getInstance().setAppStatus(AppStatusConstant.STATUS_NORMAL); //进入应用初始化正常状态-设置成正常(未回收)状态
        super.onCreate(savedInstanceState);
        AppData.HOME_LOCKED = true;
        SPEx.setFingerAuth(false);

        if (SafeUilts.isOpenSageVerify()) {//开启了指纹或者手势
            AppData.isFirstLaunch = true;
        }
        //StatusBarExtUtil.setStatusColor(this,false,true,R.color.blue2);


        //StatusBarExtUtil.setStatusColor(this,false,true,R.color.white);



    }


    @Override
    protected void initView() {
        super.initView();
        if(BuildConfig.DEBUG) {
            viewFinder.find(R.id.root_view).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getPresenter().bBlocked = true;
                    showServerSelectDlg();
                }
            });
        }
        launchBgView = viewFinder.imageView(R.id.launch_bg);
        loadLaunchBg();

        btnSkip = viewFinder.textView(R.id.btn_skip);

        startShowCountDownTimer();
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.textView(R.id.btn_skip).setOnClickListener(this);
    }

    private void loadLaunchBg() {
//        https://static.bhfastime.com/bhop/image/NA6eIkv7Ohc-4ucUpqY9V-UTbSBXlnEStZhFL_83A18.png
        String launchBgFilePath = MMKVManager.getInstance().mmkv().decodeString("launch_bg_file_path_"+ RateAndLocalManager.GetInstance(BHexApplication.getInstance()).getCurLocalKind().code);

//        String launchBgUrl = "https://static.bhfastime.com/bhop/image/NA6eIkv7Ohc-4ucUpqY9V-UTbSBXlnEStZhFL_83A18.png";
//        if (!TextUtils.isEmpty(launchBgUrl)) {
//
//            Glide.with(this)
//                    .load(launchBgUrl)
//                    .fitCenter()
//                    .placeholder(R.mipmap.launch_bg)
//                    .error(R.mipmap.launch_bg)
//                    .fallback(R.mipmap.launch_bg)
//                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
//                    .into(launchBgView);
//        }
        boolean supportNewSplash = BasicFunctionsUtil.getBasicFunctionsConfig().isSupportNewSplash();
        if (!TextUtils.isEmpty(launchBgFilePath)) {
            File launchImgFile = new File(launchBgFilePath);
            if (launchImgFile.exists()) {
                //有缓存启动图文件
                Glide.with(this)
                        .load(launchImgFile)
                        .fitCenter()
                        .error(R.mipmap.launch_bg)
                        .fallback(R.mipmap.launch_bg)
                        .into(launchBgView);

                return;
            }
        }
        //没有缓存启动页,设置默认图
        if (supportNewSplash) {//配置了新启动图，那就居中适配fitCenter
            launchBgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        }else{//没有配置，就大图裁边
            launchBgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        }
        launchBgView.setImageResource(R.mipmap.launch_bg);
    }

    @Override
    protected boolean translucentStatusBar() {
        return true;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            getPresenter().exit();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void showServerSelectDlg() {
        CustomListAlertDialog.Builder builder = new CustomListAlertDialog.Builder(this);
        String[] itemStrings = new String[]{getResources().getString(R.string.test_server) + REST_URL_TEST,
                getResources().getString(R.string.dev_server) + REST_URL_DEV, getResources().getString(R.string.prev_server) + REST_URL_PREV,
                getResources().getString(R.string.online_server) + REST_URL_ONLINE};
        builder.setItems(itemStrings, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        UrlsConfig.initUrls(UrlsConfig.ServerType.TEST_SERVER);
                        Toast.makeText(SplashActivity.this, "切换到测试服务器环境 ", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                        break;
                    case 1:
                        UrlsConfig.initUrls(UrlsConfig.ServerType.DEV_SERVER);
                        Toast.makeText(SplashActivity.this, "切换到开发服务器 ", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                        break;
                    case 2:
                        UrlsConfig.initUrls(UrlsConfig.ServerType.PREV_SERVER);
                        Toast.makeText(SplashActivity.this, "切换到预发服务器 ", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                        break;
                    case 3:
                        UrlsConfig.initUrls(UrlsConfig.ServerType.ONLINE_SERVER);
                        Toast.makeText(SplashActivity.this, "切换到线上服务器 ", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                        break;
                    default:
                        break;
                }
                SplashActivity.this.getPresenter().startApp();
            }

        });

        builder.setTitle(getResources().getString(R.string.server_choice) + API_SERVER_URL);
        builder.create().show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //APPConfig.getInstance().initUmengShare();
        //APPConfig.getInstance().initDeepKnow();
    }

    @Override
    protected boolean isStatusColorDefault() {
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_skip:
                if (showCountDownTimer != null) {
                    showCountDownTimer.cancel();
                }
                SplashActivity.this.getPresenter().startApp();
                break;
        }
    }

    private void startShowCountDownTimer() {
        String lastSeconds = MMKVManager.getInstance().mmkv().decodeString("ads_show_time",DEFAULT_SHOW_DURATION_TIME);
        Long remainingTime = new BigDecimal(lastSeconds).multiply(new BigDecimal("1000")).longValue();
//        Long remainingTime = Long.valueOf(lastSeconds) * 1000;
        if (remainingTime < 2000) {    //小于2s就不做倒计时提示了
            btnSkip.setVisibility(View.GONE);
        }else{
            btnSkip.setVisibility(View.VISIBLE);
        }
        if (remainingTime > 0) {
            if (showCountDownTimer != null) {
                return;
            }
            showCountDownTimer = new CountDownTimer(remainingTime, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    int s = (int) (millisUntilFinished / 1000);
                    String remainingTime = s + "s";
                    TextColorUtils.setTextViewColor(btnSkip, "%s " + getString(R.string.string_skip), remainingTime, R.color.blue);
                }

                @Override
                public void onFinish() {
//                    btnSkip.setText(getString(R.string.string_skip));
                    SplashActivity.this.getPresenter().startApp();

                }

            }.start();

        } else {
            SplashActivity.this.getPresenter().startApp();
        }
    }
}
